package cn.heyige.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.heyige.backend.entity.MemberOrderDO;
import cn.heyige.backend.mapper.MemberOrderMapper;
import cn.heyige.backend.service.MemberOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Optional;

/**
 * 会员订单服务实现类 - 精简版
 *
 * 专注于核心会员订单管理功能，提高系统性能和可维护性
 * 增强数据验证和错误处理
 *
 * @author CodeBuddy
 */
@Service("memberOrderService")
@Slf4j
@RequiredArgsConstructor
public class MemberOrderServiceImpl extends ServiceImpl<MemberOrderMapper, MemberOrderDO> implements MemberOrderService {
    
    private final MemberOrderMapper memberOrderMapper;
    
    @Override
    public Optional<MemberOrderDO> findByIdAndUserId(Long id, Long userId) {
        // 参数校验
        if (id == null) {
            log.warn("查询会员订单失败：订单ID为空");
            return Optional.empty();
        }

        if (userId == null) {
            log.warn("查询会员订单失败：用户ID为空");
            return Optional.empty();
        }

        try {
            LambdaQueryWrapper<MemberOrderDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MemberOrderDO::getId, id)
                    .eq(MemberOrderDO::getUserId, userId);
            return Optional.ofNullable(memberOrderMapper.selectOne(queryWrapper));
        } catch (Exception e) {
            log.error("查询会员订单失败：id={}, userId={}", id, userId, e);
            return Optional.empty();
        }
    }
    
    @Override
    public Page<MemberOrderDO> findByUserIdOrderByCreatedAtDesc(Long userId, Page<MemberOrderDO> page) {
        // 参数校验
        if (userId == null) {
            log.warn("查询会员订单列表失败：用户ID为空");
            return new Page<>(page.getCurrent(), page.getSize());
        }

        if (page == null) {
            log.warn("查询会员订单列表失败：分页参数为空");
            return new Page<>(1, 20);
        }

        try {
            LambdaQueryWrapper<MemberOrderDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MemberOrderDO::getUserId, userId)
                    .orderByDesc(MemberOrderDO::getCreateTime);
            return memberOrderMapper.selectPage(page, queryWrapper);
        } catch (Exception e) {
            log.error("查询会员订单列表失败：userId={}", userId, e);
            return new Page<>(page.getCurrent(), page.getSize());
        }
    }
}